<template>
  <div class="app-container">
    <div class="filter-container top">
      <el-select v-model="listQuery.viewpoint" placeholder="请选择视角" clearable class="filter-item">
        <el-option v-for="item in viewpoints" :key="item.id" :label="item.des" :value="item.id"/>
      </el-select>
      <el-input v-model="listQuery.goodsName" placeholder="商品名" style="width: 200px; margin-right: 20px;"
                class="filter-item"
                @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"
                 @click="handleDownload"
      >
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="index" prop="index" label="序号" align="center" width="80"/>

      <el-table-column label="商品名" min-width="150px" prop="goodsName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.goodsName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品封面" min-width="150px" prop="coverUrl">
        <template slot-scope="{row}">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.coverUrl"
            fit="contain"
            :preview-src-list="[row.coverUrl]"
          ></el-image>
        </template>
      </el-table-column>

      <el-table-column label="买家" min-width="150px" prop="buyerName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.buyerName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="卖家" min-width="150px" prop="sellerName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.sellerName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品类别" min-width="150px" prop="goodsTypeName">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.goodsTypeName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="交易状态" min-width="150px" prop="publisherName">
        <template slot-scope="{row}">
          <span class="link-type">{{ status[row.status].des }}</span>
        </template>
      </el-table-column>

      <el-table-column label="交易情况" min-width="150px" prop="tradingInfo">
        <template slot-scope="{row}">
          <el-popover
            v-if="row.des || row.reply"
            placement="bottom"
            title="交易情况"
            width="500"
            trigger="click"
          >
            <div>
              <el-tag>买家留言</el-tag>
              <el-card shadow="hover" style="margin-top: 10px;">
                {{ row.des }}
              </el-card>
              <el-divider></el-divider>
              <el-tag>卖家回复</el-tag>
              <el-card shadow="hover" style="margin-top: 10px;">
                {{ row.reply }}
              </el-card>
            </div>
            <el-button type="text" slot="reference">查看详情</el-button>
          </el-popover>
          <span v-else>无交易信息</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button
            v-if="listQuery.viewpoint === 1"
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
            :disabled="!(row.status === 0) && (userId !== row.creator)"
          >
            编辑
          </el-button>
          <el-button
            v-if="listQuery.viewpoint === 0"
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
            :disabled="(row.status !== 0) || (userId !== row.goodsPublisherId)"
          >
            审核
          </el-button>
          <el-button v-if="row.status!=='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 500px; margin-left:50px;"
      >
        <el-form-item v-if="listQuery.viewpoint === 1" label="买家留言" prop="goodsName">
          <el-input type="textarea" :rows="6" v-model="temp.des"/>
        </el-form-item>

        <el-form-item v-if="listQuery.viewpoint === 0" label="卖家回复" prop="goodsDes">
          <el-input type="textarea" :rows="6" v-model="temp.reply"/>
        </el-form-item>

        <el-form-item v-if="listQuery.viewpoint === 0" label="审核情况" prop="goodsType">
          <el-select v-model="temp.status" placeholder="请选择审核情况" clearable class="filter-item">
            <el-option v-for="item in tradingType" :key="item.id" :label="item.des" :value="item.id"/>
          </el-select>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsTradingRestfull } from '@/api/goods-trading'
import { goodsTypeRestfull } from '@/api/goods-type'
import { mapGetters } from 'vuex'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { uploadFile, removeFile } from '@/api/file'
import UUID from '@/utils/uuid'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import GaoDeMap from '@/components/GaoDeMap'
import MapShow from '@/components/GaoDeMap/MapShow'

export default {
  name: 'GoodsTrading',
  components: { GaoDeMap, MapShow, Pagination },
  directives: { waves },
  filters: {
    parseTime
  },
  data() {
    return {
      goodsType: [],
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageSize: 10,
        goodsName: undefined,
        viewpoint: 0
      },
      rules: [],
      status: [{
        id: 0,
        des: '待卖家审核'
      }, {
        id: 1,
        des: '交易成功'
      }, {
        id: 2,
        des: '卖家拒绝'
      }
      ],
      temp: {
        id: undefined,
        status: undefined,
        des: undefined,
        reply: undefined
      },
      tempCoverUrl: undefined,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '交易审核',
        create: '添加商品'
      },
      downloadLoading: false,
      viewpoints: [{ id: 0, des: '卖家视角' }, { id: 1, des: '买家视角' }],
      tradingType: [{ id: 0, des: '请选择审核状态' }, { id: 1, des: '交易成功' }, { id: 2, des: '卖家拒绝' }]
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    this.getList()
    this.getGoodsType()
    console.log(this.userId)
  },
  methods: {
    getList() {
      this.listLoading = true
      goodsTradingRestfull.fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getGoodsType() {
      goodsTypeRestfull.fetchAll(this.listQuery).then(response => {
        this.goodsType = response.data
      })
    },
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        status: 0,
        des: undefined,
        reply: undefined
      }
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.tempCoverUrl = row.coverUrl
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$refs.uploadCover.clearFiles()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          goodsTradingRestfull.updateData(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '审核完成',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsTradingRestfull.removeData(row.id).then(() => {
          this.list.splice(index, 1)
          this.total -= 1
          this.$notify({
            title: '成功',
            message: '交易删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/utils/excel-export').then(exportExcel => {
        const tHeader = {
          id: 'id',
          goodsName: '商品'
        }
        exportExcel.exportExcel(tHeader, this.list, 'goodsName')
      })
      this.downloadLoading = false
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }

  }
}
</script>

<style lang="scss" scoped>
.el-button--mini {
  padding: 7px 10px;
  min-width: 60px;
}

.top {
  margin-bottom: 20px;
}

#map {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 200px;
}
</style>
